package com.werdior.shiro.service.impl;


import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.werdior.common.exception.weirdorException;
import com.werdior.common.util.Constant;
import com.werdior.shiro.entity.User;
import com.werdior.shiro.entity.UserRole;
import com.werdior.shiro.mapper.UserMapper;
import com.werdior.shiro.mapper.UserRoleMapper;
import com.werdior.shiro.service.IRoleService;
import com.werdior.shiro.service.IUserRoleService;
import com.werdior.shiro.service.IUserService;
import com.werdior.shiro.utils.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * user 用户表 服务实现类
 * </p>
 *
 * @author werdior
 * @since 2017-12-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IRoleService roleService;

    @Override
    public boolean addUser(User user) {
        String salt = String.valueOf(System.currentTimeMillis());
        SimpleHash password = new SimpleHash("MD5", user.getPassword(), salt.toString());
        user.setSalt(salt.toString());
        user.setPassword(password.toString());

        checkRole(ShiroUtils.getUser());
        Integer result = baseMapper.insert(user);
         //保存用户与角色关系
        userRoleService.saveOrUpdate(user.getId(), user.getRoleIdList());
        if (result >= 1) {
            return true;
        }
        return false;
    }

    @Override
    public boolean updateUser(User user) {
        if(StringUtils.isBlank(user.getPassword())){
            user.setPassword(null);
        }else{
            SimpleHash password = new SimpleHash("MD5", user.getPassword(), user.getSalt().toString());
            user.setPassword(password.toString()) ;
        }
        checkRole( ShiroUtils.getUser());
        Integer result = baseMapper.updateById(user);
        userRoleService.saveOrUpdate(user.getId(), user.getRoleIdList());
        if (result >= 1) {
            return true;
        }
        return false;
    }

    @Transactional
    @Override
    public boolean deleteUserByIdAndRole(Long [] id) {
        // 拼接用户表删除list
        List<Long> userId = new ArrayList<>();
        for (Long item:id) {
            userId.add(item);
        }
        // 删除用户表数据
        Integer integer = baseMapper.deleteBatchIds(userId);
        if (integer >= 1) {
            return true;
        }
        // 删除用户角色关联表数据
        EntityWrapper<UserRole> userRoleEntityWrapper = new EntityWrapper<>();
        userRoleEntityWrapper.in("uid", id);
        userRoleMapper.delete(userRoleEntityWrapper);

        return true;
    }

    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        EntityWrapper<User> ew=new EntityWrapper<>();
        ew.where("id={0} ",userId).and().where("password={0}",password);
        User sysUser=new User();
        sysUser.setPassword(newPassword);
        return super.update(sysUser,ew);
    }

    @Override
    public List<User> selectAll() {
        EntityWrapper<User> ew=new EntityWrapper<>();
        return super.selectList(ew);
    }

    @Override
    public User selectById(Long userId) {
        return super.selectById(userId);
    }


    /**
     * 检测登录名是否重复
     *
     * @param loginName
     * @param id
     * @return
     */
    @Override
    public Boolean checkLoginName(String loginName, Long id) {
        User user = selectOne(Condition.create().eq("username", loginName));
        return user == null || !id.equals(0L) && user.getId().equals(id);
    }



    /**
     * 检查角色是否越权
     */
    private void checkRole(User user){
        //如果不是超级管理员，则需要判断用户的角色是否自己创建
        if(user.getCreateId() == Constant.SUPER_ADMIN){
            return ;
        }

        //查询用户创建的角色列表
        List<Long> roleIdList = roleService.queryRoleIdList(user.getCreateId());

        //判断是否越权
        if(!roleIdList.containsAll(user.getRoleIdList())){
            throw new weirdorException("新增用户所选角色，不是本人创建");
        }
    }
}
